package main.javassist.lombok;

import javassist.*;
import main.javassist.lombok.annotation.Getter;
import main.javassist.lombok.annotation.Setter;

public class Lombok {

    public static void generater(String className) throws
            Exception{

    //1. 根据类上的标识设置判断依据变量
    Class<?> cls = Class.forName(className);
    boolean isGetter = false;
		if(cls.isAnnotationPresent(Getter .class))

    {
        isGetter = true;
    }

    boolean isSetter = false;
		if(cls.isAnnotationPresent(Setter .class))

    {
        isSetter = true;
    }

    //2. 通过javassist获取所有私有属性，根据注解来判断是否添加get或set方法
    ClassPool pool = ClassPool.getDefault();
    CtClass ct = pool.get(cls.getName());
		ct.defrost();        //解冻，才能修改类

    CtField[] fields = ct.getDeclaredFields();
		for(
    CtField field :fields)

    {
        String fieldname = toFirstUpperCase(field.getName());

        //3. 处理get
        if (isGetter) {
            CtMethod getter = new CtMethod(pool.get(field.getType().getName()),
                    "get" + fieldname, null, ct);
            getter.setModifiers(Modifier.PUBLIC);
            getter.setBody("{ return this." + field.getName() + "; }");

            //? 担心可能已经创建过getter方法，简单判断
            try {
                ct.addMethod(getter);
            } catch (Exception e) {

            }
        }

        //4. 处理set
        if (isSetter) {
            CtMethod setter = new CtMethod(CtClass.voidType,
                    "set" + fieldname,
                    new CtClass[]{pool.get(field.getType().getName())}, ct);
            setter.setModifiers(Modifier.PUBLIC);
            setter.setBody("{ this." + field.getName() + "=$1; }");

            try {
                ct.addMethod(setter);
            } catch (Exception e) {

            }
        }
    }

    //5. 写类
		ct.writeFile("bin/");
		ct.freeze();        //冻结，类不允许修改

}
    private static String toFirstUpperCase(String name) {
        return (""+name.charAt(0)).toUpperCase()+name.substring(1);
    }


}
